<?php
/**
 * Created by PhpStorm.
 * User: chency
 * Date: 2019/8/3
 * Time: 14:15
 */

namespace app\index\service;

use think\cache\driver\Redis;
use think\Config;
use think\Model;

class WechatService extends Model {
    public $wechatConfig = [
        "token"          => "d39070c2bb4e4ba105be8165269b1b37",
        "EncodingAESKey" => "8Qh6cADSJUWeUbkynnlWbFZxzkDWbneFeTsq54urDG5"
    ];

    //获取access_token
    public function getAccessToken() {
        $redis       = new Redis();
        $accessToken = $redis->get("globals:wechat:access_token");
        if (empty($accessToken)) {
            //请求一个新的access_token
            $appId  = Config::get("wechat_app_id");
            $secret = Config::get("wechat_secret");
            $url    = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appId . "&secret=" . $secret;
            $res    = json_decode($this->httpGet($url), true);
            if (empty($res['access_token'])) {
                $redis->set('globals:wechat:access_token', $res['access_token'], $res['expires_in']);
            }
        }
        return $accessToken;
    }

    private function getJsApiTicket() {
        $redis  = new Redis();
        $ticket = $redis->get("globals:wechat:ticket");
        if (empty($ticket)) {
            $url    = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=" . $this->getAccessToken();
            $res    = json_decode($this->httpGet($url), true);
            $ticket = $res['ticket'];
            if(!empty($ticket)){
                $redis->set('globals:wechat:ticket', $ticket, 3600);
            }
        }
        return $ticket;
    }

    public function getJSSDKInfo() {
        $protocol = (!empty($_SERVER["HTTP_X_CLIENT_SCHEME"]) && $_SERVER["HTTP_X_CLIENT_SCHEME"] == "https") ? "https://" : "http://";
        $url      = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $jsapiTicket = $this->getJsApiTicket();
        $timestamp   = time();
        $chars       = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $nonceStr    = "";
        for ($i = 0; $i < 16; $i++) {
            $nonceStr .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        $signature = sha1($string);
        $signPackage = array(
            "appId"     => Config::get("wechat_app_id"),
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;

    }

    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
}